package com.example.administrator.im.adapter;

import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.example.administrator.im.R;
import com.example.administrator.im.activity.ChatActivity;

import java.io.IOException;
import java.util.List;

/**
 * 作者：wp
 * 时间：2016/4/18 18:08
 * 描述：TODO
 */
public class ChatMessageAdapter extends BaseAdapter implements Handler.Callback {

    private static final String REFRESH_LIST = "refresh_list";
    private static final String REFRESH_LIST_LAST = "refresh_list_last";
    private static final int MESSAGE_RECVIVE_TEXT = 0;
    private static final int MESSAGE_SEND_TEXT = 1;
    private static final int MESSAGE_RECVIVE_VOICE = 2;
    private static final int MESSAGE_SEND_VOICE = 3;

    private Context mContent;
    private List<EMMessage> listMsgs;
    private LayoutInflater inflater;
    private EMConversation conversation;
    private Handler handler;
    private MediaPlayer player;

    public ChatMessageAdapter(Context context, String username, List<EMMessage> listMsgs) {
        this.mContent = context;
        inflater = LayoutInflater.from(context);
        this.conversation = EMChatManager.getInstance().getConversation(username);
        this.listMsgs = conversation.getAllMessages();
        handler = new Handler(Looper.myLooper(),this);

    }

    @Override
    public int getItemViewType(int position) {
        EMMessage msg = (EMMessage) getItem(position);
        if (msg.getType() == EMMessage.Type.TXT) {
            return msg.direct == EMMessage.Direct.RECEIVE ? MESSAGE_RECVIVE_TEXT : MESSAGE_SEND_TEXT;
        }
        if(msg.getType() == EMMessage.Type.VOICE) {
            return msg.direct == EMMessage.Direct.RECEIVE ? MESSAGE_RECVIVE_VOICE : MESSAGE_SEND_VOICE;
        }
        return super.getItemViewType(position);
    }

    @Override
    public int getViewTypeCount() {
        return 4;
    }

    @Override
    public int getCount() {
        return listMsgs.size();
    }

    @Override
    public Object getItem(int position) {
        return listMsgs.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;
        int type = getItemViewType(position);
        if (convertView == null) {
            holder = new ViewHolder();
            switch (type) {
                case MESSAGE_RECVIVE_TEXT:
                    convertView = inflater.inflate(R.layout.chat_message_recvice_text, parent, false);
                    holder.chatMsgFormText = (TextView) convertView.findViewById(R.id.chat_msg_form_text);
                    holder.userFormHeader = (ImageView) convertView.findViewById(R.id.user_form_header);
                    convertView.setTag(holder);
                    break;
                case MESSAGE_SEND_TEXT:
                    convertView = inflater.inflate(R.layout.chat_message_send_text, parent, false);
                    holder.chatMsgToText = (TextView) convertView.findViewById(R.id.chat_msg_to_text);
                    holder.userToHeader = (ImageView) convertView.findViewById(R.id.user_to_header);
                    convertView.setTag(holder);
                    break;
                case MESSAGE_RECVIVE_VOICE:
                    convertView = inflater.inflate(R.layout.chat_message_recvice_voice, parent, false);
                    holder.rlReciveVoice = (RelativeLayout) convertView.findViewById(R.id.rl_recive_voice);
                    holder.ivReciveVoice = (ImageView) convertView.findViewById(R.id.iv_recive_voice);
                    holder.voiceReciveTime = (TextView) convertView.findViewById(R.id.voice_recive_time);
                    holder.voiceReciveRedPoint = (ImageView) convertView.findViewById(R.id.voice_recive_red_point);
                    convertView.setTag(holder);
                    break;
                case MESSAGE_SEND_VOICE:
                    convertView = inflater.inflate(R.layout.chat_message_send_voice, parent, false);
                    holder.rlSendVoice = (RelativeLayout) convertView.findViewById(R.id.rl_send_voice);
                    holder.ivSendVoice = (ImageView) convertView.findViewById(R.id.iv_send_voice);
                    holder.voiceSendTime = (TextView) convertView.findViewById(R.id.voice_send_time);
                    holder.voiceSendRedPoint = (ImageView) convertView.findViewById(R.id.voice_send_red_point);
                    convertView.setTag(holder);
                    break;
            }
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        switch (type) {
            case MESSAGE_RECVIVE_TEXT:
            case MESSAGE_SEND_TEXT:
                TextMessageBody body = (TextMessageBody) listMsgs.get(position).getBody();
                if(null != holder.chatMsgFormText)
                    holder.chatMsgFormText.setText(body.getMessage());
                if(null != holder.chatMsgToText)
                    holder.chatMsgToText.setText(body.getMessage());
                break;
            case MESSAGE_RECVIVE_VOICE:
            case MESSAGE_SEND_VOICE:
                final VoiceMessageBody voicBody = (VoiceMessageBody) listMsgs.get(position).getBody();
                final int length = voicBody.getLength();
                if(length > 0) {
                    if(null != holder.voiceReciveTime) {
                        holder.voiceReciveTime.setText(length + "\"");
                        holder.voiceReciveTime.setVisibility(View.VISIBLE);
                    }
                    if(null != holder.voiceSendTime) {
                        holder.voiceSendTime.setText(length + "\"");
                        holder.voiceSendTime.setVisibility(View.VISIBLE);
                    }
                }
                if(null != holder.voiceReciveRedPoint) {
                    if(listMsgs.get(position).isListened()) {
                        holder.voiceReciveRedPoint.setVisibility(View.INVISIBLE);
                    } else {
                        holder.voiceReciveRedPoint.setVisibility(View.INVISIBLE);
                    }
                }
                if(null != holder.voiceSendRedPoint) {
                    if(listMsgs.get(position).isListened()) {
                        holder.voiceSendRedPoint.setVisibility(View.INVISIBLE);
                    } else {
                        holder.voiceSendRedPoint.setVisibility(View.INVISIBLE);
                    }
                }

                if(null != holder.rlReciveVoice) {
                    holder.rlReciveVoice.setOnClickListener(new View.OnClickListener() {
                        AnimationDrawable voiceAnimation;
                        @Override
                        public void onClick(View v) {
                            player = new MediaPlayer();
                            holder.ivReciveVoice.setImageResource(R.drawable.voice_from_icon);
                            voiceAnimation = (AnimationDrawable) holder.ivReciveVoice.getDrawable();
                            voiceAnimation.start();
                            PlayVoice(voicBody);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    voiceAnimation.stop();
                                    player.release();
                                    player = null;
                                    holder.ivReciveVoice.setImageResource(R.drawable.chatfrom_voice_playing);
                                }
                            }, length * 1000 + 300);
                        }
                    });
                }
                if(null != holder.rlSendVoice) {
                    holder.rlSendVoice.setOnClickListener(new View.OnClickListener() {
                        AnimationDrawable voiceAnimation;
                        @Override
                        public void onClick(View v) {
                            player = new MediaPlayer();
                            holder.ivSendVoice.setImageResource(R.drawable.voice_to_icon);
                            voiceAnimation = (AnimationDrawable) holder.ivSendVoice.getDrawable();
                            voiceAnimation.start();
                            PlayVoice(voicBody);
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    voiceAnimation.stop();
                                    player.release();
                                    player = null;
                                    holder.ivSendVoice.setImageResource(R.drawable.chatto_voice_playing);
                                }
                            },length * 1000 + 300);
                        }
                    });

                }
                break;
        }

        return convertView;
    }

    /**
     * 播发录音
     * @param voicBody
     */
    private void PlayVoice(VoiceMessageBody voicBody) {
        try {
            player.setDataSource(voicBody.getLocalUrl());
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void refreshList() {
        if(null != handler){
            Message message = handler.obtainMessage();
            message.obj = REFRESH_LIST;
            handler.sendMessage(message);
        }
    }

    public void refreshSelectLast() {
        Message message = handler.obtainMessage();
        message.obj = REFRESH_LIST_LAST;
        handler.sendMessage(message);
    }

    @Override
    public boolean handleMessage(Message msg) {
        if(msg.obj == REFRESH_LIST) {
            notifyDataSetChanged();
        }
        if(msg.obj == REFRESH_LIST_LAST) {
            ListView listView = ((ChatActivity)mContent).getListView();
            if (listMsgs.size() > 0) {
                listView.setSelection(listMsgs.size() - 1);
            }
        }
        return false;
    }

    class ViewHolder {
        ImageView userFormHeader;
        TextView chatMsgFormText;
        TextView chatMsgToText;
        ImageView userToHeader;
        //接收
        RelativeLayout rlReciveVoice;
        ImageView ivReciveVoice;
        TextView voiceReciveTime;
        ImageView voiceReciveRedPoint;
        //发送
        RelativeLayout rlSendVoice;
        ImageView ivSendVoice;
        TextView voiceSendTime;
        ImageView voiceSendRedPoint;

    }
}
